package cn.witque.controller;

import cn.witque.config.WxPayConfig;
import cn.witque.pojo.ItripHotelOrder;
import cn.witque.pojo.dto.Dto;
import cn.witque.service.OrderService;
import cn.witque.utils.DtoUtil;
import cn.witque.wxutil.WXPayRequest;
import cn.witque.wxutil.WXPayUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/wxpay/")
public class WXPayController {


    @Resource
    private OrderService orderService;

    @Resource
    private WxPayConfig wxPayConfig;


    @RequestMapping(value = "/createqccode/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public Dto createQcCode(@PathVariable String orderNo, HttpServletResponse response) {
        ItripHotelOrder order = null;
        Map<String, String> data = new HashMap<String, String>();
        Map<String, Object> result = new HashMap<String, Object>();
        WXPayRequest wxPayRequest = new WXPayRequest(this.wxPayConfig);
        try {
            order = orderService.loadOrder(orderNo);
            if (order == null || order.getOrderStatus() != 0) {
                return DtoUtil.getFailed("订单状态异常", "150");
            }

            String totalMoney = order.getPayAmount().toString().replace(".","");
            data.put("body", "爱旅行项目订单支付");
            data.put("out_trade_no", orderNo);
            data.put("device_info", "");
            data.put("total_fee", totalMoney);
            data.put("spbill_create_ip", "47.92.146.135");
            data.put("notify_url", "http://itrip.project.bdqn.cn/trade/api/wxpay/notify");
            Map<String, String> r = wxPayRequest.unifiedorder(data);
            String resultCode = r.get("result_code");
            if (resultCode.equals("SUCCESS")) {
                result.put("hotelName", order.getHotelName());
                result.put("roomId", order.getRoomId());
                result.put("count", order.getCount());
                result.put("payAmount", order.getPayAmount());
                result.put("codeUrl", r.get("code_url"));
                return DtoUtil.getSuccess(result);
            } else {
                return DtoUtil.getFailed("订单支付异常", "151");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.getFailed("订单运行异常", "152");
        }
    }




    /**
     * 获取订单状态
     * @param orderNo
     * @return
     */
    @RequestMapping(value = "/queryorderstatus/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public Dto queryOrderIsSuccess(@PathVariable String orderNo) {
        ItripHotelOrder order = null;
        try {
            order = orderService.loadOrder(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.getSuccess(order);
    }


    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> paymentCallBack(HttpServletRequest request, HttpServletResponse response) {
        WXPayRequest wxPayRequest = new WXPayRequest(this.wxPayConfig);
        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> params = null;
        try {
            InputStream inputStream;
            StringBuffer sb = new StringBuffer();
            inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            inputStream.close();
            params = WXPayUtil.xmlToMap(sb.toString());
            boolean flag = wxPayRequest.isResponseSignatureValid(params);
            if (flag) {
                String returnCode = params.get("return_code");
                if (returnCode.equals("SUCCESS")) {
                    String transactionId = params.get("transaction_id");
                    String outTradeNo = params.get("out_trade_no");
                    if (!orderService.verify(outTradeNo)) {
                        orderService.paySuccess(outTradeNo, 2, transactionId);
                    }
                } else {
                    result.put("return_code", "FAIL");
                    result.put("return_msg", "支付失败");
                }
            } else {
                result.put("return_code", "FAIL");
                result.put("return_msg", "签名失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;




    }



}
